<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter, useRoute, RouterLink } from 'vue-router'
import { saveAuth } from '../utils/tools/auth.js'
import { loginApi } from '@/api/user.js'

const router = useRouter()
const route = useRoute()

const username = ref('')
const password = ref('')
const loading = ref(false)
const errorMessage = ref('')
const showPassword = ref(false)

// 清除错误信息
function clearError() {
  if (errorMessage.value) {
    errorMessage.value = ''
  }
}

// 隐藏浏览器默认密码按钮的函数
function hideBrowserPasswordButton() {
  const passwordInput = document.querySelector('input[type="password"]')
  if (passwordInput) {
    // 强制隐藏浏览器默认按钮
    passwordInput.style.setProperty('-webkit-textfield-decoration-container', 'none', 'important')
    passwordInput.style.setProperty('textfield-decoration-container', 'none', 'important')
    
    // 使用MutationObserver监听DOM变化
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.type === 'childList') {
          // 查找并移除浏览器添加的按钮
          const browserButtons = document.querySelectorAll('::-webkit-credentials-auto-fill-button')
          browserButtons.forEach(button => {
            if (button.parentElement === passwordInput.parentElement) {
              button.remove()
            }
          })
        }
      })
    })
    
    // 开始观察
    observer.observe(passwordInput.parentElement, {
      childList: true,
      subtree: true
    })
    
    // 监听输入事件，持续隐藏
    passwordInput.addEventListener('input', () => {
      setTimeout(() => {
        const browserButton = passwordInput.parentElement?.querySelector('::-webkit-credentials-auto-fill-button')
        if (browserButton) {
          browserButton.remove()
        }
      }, 10)
    })
  }
}

// 组件挂载后执行
onMounted(() => {
  nextTick(() => {
    hideBrowserPasswordButton()
  })
})

function validate() {
  if (!username.value.trim()) return '请输入用户名'
  if (!password.value) return '请输入密码'
  if (password.value.length < 6) return '密码至少 6 位'
  return ''
}

async function onSubmit() {
  errorMessage.value = ''
  const err = validate()
  if (err) {
    errorMessage.value = err
    return
  }
  loading.value = true
  try {
    // 先测试后端连接
    console.log('开始登录请求...')
    console.log('用户名:', username.value.trim())
    console.log('密码:', password.value)
    
    // 调用后端登录API
    const response = await loginApi(username.value.trim(), password.value)
    
    if (response.code === 200) {
      // 登录成功，保存用户信息
      const user = {
        user_id: response.data.user_id,
        username: response.data.user_name,
        user_jurisdiction: response.data.user_jurisdiction
      }
      saveAuth(user)
      const redirect = (route.query.redirect && String(route.query.redirect)) || '/home'
      router.replace(redirect)
    } else {
      // 登录失败，显示后端返回的错误信息
      errorMessage.value = response.message || '登录失败'
    }
  } catch (e) {
    console.error('登录错误:', e)
    console.log('错误状态码:', e.status)
    console.log('错误消息:', e.message)
    
    // 处理不同类型的错误 - 按优先级排序
    if (e.status === 400) {
      errorMessage.value = '用户名和密码不能为空'
    } else if (e.status === 404) {
      errorMessage.value = '用户不存在'
    } else if (e.status === 401) {
      errorMessage.value = '账号或密码错误'
    } else if (e.message.includes('Failed to fetch') || e.message.includes('NetworkError')) {
      errorMessage.value = '无法连接到服务器，请检查网络连接'
    } else if (e.message.includes('Request failed 404')) {
      errorMessage.value = '用户不存在'
    } else if (e.message.includes('Request failed 401')) {
      errorMessage.value = '账号或密码错误'
    } else if (e.message.includes('Request failed 400')) {
      errorMessage.value = '用户名和密码不能为空'
    } else {
      // 直接使用后端返回的错误信息
      errorMessage.value = e.message || '登录失败，请稍后重试'
    }
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="auth-container">
    <div class="split">
      <div class="panel image left" data-animate="slide-left">
        <div class="image-mask"></div>
      </div>
      <div class="panel form right" data-animate="slide-right">
        <div class="card">
          <div class="brand">
            <div class="logo">K</div>
            <div class="brand-text">
              <h2>KMS 登录</h2>
              <p class="subtitle">欢迎回来，请登录您的账户</p>
            </div>
          </div>

          <form @submit.prevent="onSubmit" class="form" aria-label="登录表单">
            <div class="socials">
              <button type="button" class="social google" aria-label="Google 登录">
                <svg viewBox="0 0 24 24"><path fill="currentColor" d="M21.35 11.1H12v2.9h5.35c-.23 1.48-1.61 4.34-5.35 4.34c-3.22 0-5.85-2.67-5.85-5.97S8.78 6.4 12 6.4c1.84 0 3.09.78 3.8 1.45l2.6-2.5C17.22 3.7 14.86 2.8 12 2.8C6.92 2.8 2.8 6.95 2.8 12s4.12 9.2 9.2 9.2c5.3 0 8.8-3.72 8.8-8.97c0-.6-.06-1.02-.15-1.13Z"/></svg>
                使用 Google 登录
              </button>
              <button type="button" class="social wechat" aria-label="微信登录">
                <svg viewBox="0 0 24 24"><path fill="currentColor" d="M9.5 5C5.91 5 3 7.24 3 10c0 1.5.84 2.86 2.18 3.79L4.5 16.5l2.98-.93c.62.17 1.28.26 2.02.26c3.59 0 6.5-2.24 6.5-4.99S13.09 5 9.5 5m-2 3a.75.75 0 1 1 0 1.5A.75.75 0 0 1 7.5 8m4 0a.75.75 0 1 1 0 1.5A.75.75 0 0 1 11.5 8M20 10.5c0 2.13-1.53 3.96-3.74 4.67c.09.31.15.64.15.98c0 .31-.05.61-.12.9L18.5 18l-2.1.7c-.43.12-.9.18-1.4.18c-2.93 0-5.3-1.78-5.55-4.04c.8.17 1.65.26 2.55.26C15.09 15.1 18 13.03 18 10.5c0-.69-.18-1.35-.5-1.95C19.2 8.95 20 9.65 20 10.5m-3.25-.75a.75.75 0 1 1 0 1.5a.75.75 0 0 1 0-1.5Z"/></svg>
                使用微信登录
              </button>
            </div>
            <div class="divider"><span>或</span></div>
            <label class="field">
              <span>用户名</span>
              <div class="input-wrapper">
                <svg viewBox="0 0 24 24" class="icon" aria-hidden="true"><path fill="currentColor" d="M12 12a5 5 0 1 0-5-5a5 5 0 0 0 5 5Zm0 2c-4.418 0-8 2.239-8 5v1h16v-1c0-2.761-3.582-5-8-5Z"/></svg>
                <input v-model="username" @input="clearError" type="text" placeholder="请输入用户名" autocomplete="username" />
              </div>
            </label>

            <label class="field">
              <span>密码</span>
              <div class="input-wrapper">
                <svg viewBox="0 0 24 24" class="icon" aria-hidden="true"><path fill="currentColor" d="M17 8h-1V6a4 4 0 1 0-8 0v2H7a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-8a2 2 0 0 0-2-2Zm-6 0h2V6a2 2 0 1 0-4 0v2Zm6 10H7v-8h10v8Z"/></svg>
                <input :type="showPassword ? 'text' : 'password'" v-model="password" @input="clearError" placeholder="请输入密码" autocomplete="off" data-form-type="other" />
                <button type="button" class="toggle-btn" @click="showPassword = !showPassword" :aria-label="showPassword ? '隐藏密码' : '显示密码'">
                  <svg v-if="!showPassword" viewBox="0 0 24 24"><path fill="currentColor" d="M12 5C7 5 2.73 8.11 1 12c1.73 3.89 6 7 11 7s9.27-3.11 11-7c-1.73-3.89-6-7-11-7Zm0 12a5 5 0 1 1 0-10a5 5 0 0 1 0 10Zm0-2a3 3 0 1 0 0-6a3 3 0 0 0 0 6Z"/></svg>
                  <svg v-else viewBox="0 0 24 24"><path fill="currentColor" d="M2 5.27L3.28 4L20 20.72L18.73 22l-2.27-2.27A10.89 10.89 0 0 1 12 19c-5 0-9.27-3.11-11-7a11.7 11.7 0 0 1 5.06-5.79L2 5.27ZM12 7a5 5 0 0 1 5 5c0 .8-.19 1.55-.5 2.22L13.78 11.5A3 3 0 0 0 12 9a2.9 2.9 0 0 0-1.5.41L8.78 7.69A6.4 6.4 0 0 1 12 7Z"/></svg>
                </button>
              </div>
            </label>

            <p v-if="errorMessage" class="error" role="alert">{{ errorMessage }}</p>
            <div class="row">
              <label class="checkbox">
                <input type="checkbox" />
                <span class="checkmark"></span>
                <span class="checkbox-text">记住我</span>
              </label>
              <RouterLink class="forgot-link" to="/forgot-password">
                <svg viewBox="0 0 24 24" class="forgot-icon">
                  <path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                </svg>
                忘记密码？
              </RouterLink>
            </div>
            <button class="primary" :disabled="loading">{{ loading ? '登录中...' : '登录' }}</button>
          </form>

          <p class="switch">
            还没有账号？<RouterLink to="/register">去注册</RouterLink>
          </p>
        </div>
      </div>
    </div>
  </div>
  
</template>

<style scoped>
.auth-container {
  min-height: 100dvh;
  display: grid;
  place-items: stretch;
  background:
    radial-gradient(1200px 600px at 10% -10%, rgba(99,102,241,.22), transparent 60%),
    radial-gradient(1000px 500px at 120% 10%, rgba(56,189,248,.18), transparent 60%),
    linear-gradient(135deg, #f8fafc 0%, #eef2f7 100%);
  overflow: hidden;
}
.split { width: 100%; height: 100dvh; display: grid; grid-template-columns: 1fr 1fr; gap: 0; padding: 0; }
.panel { border-radius: 0; overflow: hidden; position: relative; }
.panel.image { background: linear-gradient(135deg, #4f46e5, #06b6d4); box-shadow: 0 20px 50px rgba(79,70,229,.25); }
.image::before { content: ''; position: absolute; inset: 0; background: url('https://images.unsplash.com/photo-1519389950473-47ba0277781c?q=80&w=1640&auto=format&fit=crop') center/cover no-repeat; opacity: .9; filter: saturate(1.05); }
.image-mask { position: absolute; inset: 0; background:
  radial-gradient(420px 420px at 18% 22%, rgba(255,255,255,.28), transparent 60%),
  linear-gradient(180deg, rgba(255,255,255,.06), rgba(255,255,255,0)); }
.panel.form { background: transparent; display: grid; align-items: center; justify-items: center; padding: 40px; }
.card {
  width: 100%;
  max-width: 460px;
  background: rgba(255,255,255,0.85);
  backdrop-filter: blur(10px);
  border-radius: 18px;
  padding: 32px;
  box-shadow: 0 24px 60px rgba(15,23,42,0.18);
  border: 1px solid rgba(99,102,241,.18);
  animation: floatIn .3s ease-out;
}
.brand { display: flex; gap: 12px; align-items: center; margin-bottom: 18px; }
.logo { width: 44px; height: 44px; border-radius: 14px; background: linear-gradient(135deg, #6366f1, #8b5cf6); color: #fff; display:grid; place-items:center; font-weight: 700; box-shadow: 0 10px 24px rgba(99,102,241,.35); }
h2 { margin: 0 0 6px; font-size: 22px; letter-spacing: .2px; color: #0f172a; }
.subtitle { margin: 0; color: #6b7280; font-size: 13px; }
.form { display: grid; gap: 14px; }
.field { display: grid; gap: 8px; }
.field span { color: #4b5563; font-size: 13px; font-weight: 600; letter-spacing: .2px; }
.input-wrapper { 
  position: relative; 
  border: 1px solid #e5e7eb; 
  border-radius: 14px; 
  background: linear-gradient(180deg, #ffffff, #f9fafb); 
  transition: border-color .2s, box-shadow .2s, background .2s, transform .1s; 
}
.input-wrapper:hover { 
  border-color: #d1d5db; 
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}
.input-wrapper:focus-within { 
  border-color: #6366f1; 
  border-width: 2px;
  box-shadow: 
    0 0 0 3px rgba(99,102,241,.12),
    0 4px 16px rgba(99,102,241,.15),
    0 1px 3px rgba(0, 0, 0, 0.1);
  background: #fff; 
  transform: translateY(-1px);
}
.icon { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); width: 18px; height: 18px; color: #9ca3af; transition: color .2s; }
.input-wrapper:focus-within .icon { color: #6366f1; }
.socials { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.social { display: grid; grid-auto-flow: column; align-items: center; justify-content: center; gap: 8px; border: 1px solid #e5e7eb; background: #fff; color: #111827; padding: 10px; border-radius: 12px; cursor: pointer; transition: box-shadow .2s, transform .05s, border-color .2s; }
.social svg { width: 18px; height: 18px; }
.social:hover { box-shadow: 0 8px 20px rgba(15,23,42,.08); border-color: #d1d5db; }
.social.google:hover { border-color: #93c5fd; }
.social.wechat:hover { border-color: #86efac; }
.divider { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; color: #9ca3af; font-size: 12px; margin: 6px 0 2px; }
.divider::before, .divider::after { content: ''; height: 1px; background: #e5e7eb; }
.row { 
  display: flex; 
  align-items: center; 
  justify-content: space-between; 
  margin-top: 8px; 
  gap: 16px;
}

/* 自定义复选框样式 */
.checkbox { 
  display: inline-flex; 
  gap: 10px; 
  align-items: center; 
  color: #6b7280; 
  font-size: 13px; 
  font-weight: 500;
  cursor: pointer;
  transition: color 0.2s ease;
  position: relative;
}

.checkbox:hover {
  color: #4f46e5;
}

.checkbox input { 
  position: absolute;
  opacity: 0;
  cursor: pointer;
  width: 0;
  height: 0;
}

.checkmark {
  width: 18px;
  height: 18px;
  border: 2px solid #d1d5db;
  border-radius: 4px;
  background: #fff;
  position: relative;
  transition: all 0.2s ease;
  flex-shrink: 0;
}

.checkbox:hover .checkmark {
  border-color: #4f46e5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

.checkbox input:checked + .checkmark {
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  border-color: #6366f1;
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.3);
}

.checkbox input:checked + .checkmark::after {
  content: '';
  position: absolute;
  left: 5px;
  top: 2px;
  width: 4px;
  height: 8px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.checkbox-text {
  user-select: none;
  transition: color 0.2s ease;
}

.checkbox input:checked ~ .checkbox-text {
  color: #4f46e5;
  font-weight: 600;
}

/* 忘记密码链接样式 */
.forgot-link { 
  color: #6b7280; 
  font-size: 13px; 
  text-decoration: none; 
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 8px;
  border-radius: 6px;
  transition: all 0.2s ease;
  font-weight: 500;
  position: relative;
  overflow: hidden;
}

.forgot-link::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(79, 70, 229, 0.1), transparent);
  transition: left 0.5s ease;
}

.forgot-link:hover::before {
  left: 100%;
}

.forgot-link:hover { 
  color: #4f46e5;
  background: rgba(79, 70, 229, 0.05);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(79, 70, 229, 0.15);
}

.forgot-icon {
  width: 14px;
  height: 14px;
  transition: transform 0.2s ease;
}

.forgot-link:hover .forgot-icon {
  transform: scale(1.1);
}
input { 
  appearance: none; 
  border: none; 
  background: transparent; 
  width: 100%; 
  border-radius: 14px; 
  padding: 12px 40px 12px 38px; 
  font-size: 14px; 
  color: #111827; 
  font-weight: 500;
  transition: color 0.2s ease;
}

/* 隐藏浏览器默认的密码显示按钮 */
input[type="password"]::-webkit-credentials-auto-fill-button,
input[type="password"]::-webkit-credentials-auto-fill-button:hover,
input[type="password"]::-webkit-credentials-auto-fill-button:active {
  display: none !important;
  visibility: hidden !important;
  opacity: 0 !important;
  pointer-events: none !important;
}

/* 隐藏Chrome的密码显示按钮 */
input[type="password"]::-webkit-textfield-decoration-container {
  display: none !important;
}

/* 隐藏Firefox的密码显示按钮 */
input[type="password"]::-moz-textfield-decoration-container {
  display: none !important;
}

/* 隐藏所有浏览器的密码显示按钮 */
input[type="password"]::-webkit-credentials-auto-fill-button {
  -webkit-appearance: none !important;
  display: none !important;
  visibility: hidden !important;
  opacity: 0 !important;
  pointer-events: none !important;
  position: absolute !important;
  right: -9999px !important;
}

/* 确保我们的自定义按钮在最上层 */
.toggle-btn {
  z-index: 999 !important;
}

/* 强制隐藏所有可能的浏览器密码按钮 */
.input-wrapper input[type="password"]::-webkit-credentials-auto-fill-button,
.input-wrapper input[type="password"]::-webkit-textfield-decoration-container,
.input-wrapper input[type="password"]::-webkit-credentials-auto-fill-button:hover,
.input-wrapper input[type="password"]::-webkit-credentials-auto-fill-button:active,
.input-wrapper input[type="password"]::-webkit-credentials-auto-fill-button:focus {
  display: none !important;
  visibility: hidden !important;
  opacity: 0 !important;
  pointer-events: none !important;
  position: absolute !important;
  right: -9999px !important;
  width: 0 !important;
  height: 0 !important;
  margin: 0 !important;
  padding: 0 !important;
  border: none !important;
  background: none !important;
  -webkit-appearance: none !important;
  appearance: none !important;
}

/* 针对动态生成的按钮 */
.input-wrapper *::-webkit-credentials-auto-fill-button {
  display: none !important;
  visibility: hidden !important;
  opacity: 0 !important;
  pointer-events: none !important;
}

/* 最强制性的隐藏规则 */
.input-wrapper::-webkit-credentials-auto-fill-button,
.input-wrapper::-webkit-textfield-decoration-container,
.input-wrapper *::-webkit-credentials-auto-fill-button,
.input-wrapper *::-webkit-textfield-decoration-container {
  display: none !important;
  visibility: hidden !important;
  opacity: 0 !important;
  pointer-events: none !important;
  position: absolute !important;
  right: -9999px !important;
  width: 0 !important;
  height: 0 !important;
  margin: 0 !important;
  padding: 0 !important;
  border: none !important;
  background: none !important;
  -webkit-appearance: none !important;
  appearance: none !important;
}

/* 针对所有可能的浏览器按钮 */
*::-webkit-credentials-auto-fill-button {
  display: none !important;
  visibility: hidden !important;
  opacity: 0 !important;
  pointer-events: none !important;
}
input::placeholder { 
  color: #9ca3af; 
  font-weight: 400;
  transition: color 0.2s ease;
}
input:focus { 
  outline: none; 
  color: #0f172a;
  font-weight: 600;
}
input:focus::placeholder {
  color: #6b7280;
}
.toggle-btn {
  position: absolute; right: 8px; top: 50%; transform: translateY(-50%);
  width: 32px; height: 32px; display: grid; place-items: center;
  background: transparent; border: none; border-radius: 10px; cursor: pointer; color: #6b7280;
  z-index: 10;
}

.toggle-btn svg {
  width: 20px;
  height: 20px;
}
.toggle-btn:hover { background: #eef2ff; color: #4f46e5; }
.panel[data-animate="slide-left"] { animation: slideInLeft .5s ease-out both; }
.panel[data-animate="slide-right"] { animation: slideInRight .5s ease-out both; }
.primary {
  margin-top: 8px;
  background: linear-gradient(135deg, #6366f1, #4338ca);
  color: #fff;
  border: none;
  padding: 12px 16px;
  font-size: 15px;
  border-radius: 12px;
  cursor: pointer;
  transition: transform .05s ease, box-shadow .2s ease, filter .2s ease;
  box-shadow: 0 10px 20px rgba(67,56,202,.35);
}
.primary:hover { filter: brightness(1.04); }
.primary:disabled { opacity: .7; cursor: not-allowed; box-shadow: none; }
.primary:active { transform: translateY(1px); }
.error { color: #ef4444; font-size: 13px; margin: 4px 0 0; }
.switch { margin-top: 14px; color: #6b7280; font-size: 14px; }

@keyframes floatIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
@keyframes slideInLeft { from { opacity: 0; transform: translateX(-18px); } to { opacity: 1; transform: translateX(0); } }
@keyframes slideInRight { from { opacity: 0; transform: translateX(18px); } to { opacity: 1; transform: translateX(0); } }

@media (max-width: 900px) {
  .split { grid-template-columns: 1fr; height: auto; }
  .panel.image { height: 220px; border-bottom-left-radius: 18px; border-bottom-right-radius: 18px; }
  .panel.form { padding: 20px; }
}
</style>


